<template>
  <div class="dialog-content" v-loading="getLoading">
    <div class="title">{{$t('subaccount.set_force_warning')}}</div>
    <div class="clearfix">
      <div class="width270 fl">
        <div class="item" :class="{gray: !list.a.checked}">
          <div class="row">
            <input type="checkbox" hidden id="checkbox1" v-model="list.a.checked">
            <label for="checkbox1" :class="language">{{$t('subaccount.force_warining')}}</label>
          </div>
          <div class="row">
            <span>{{$t('subaccount.force_low')}}</span>
            <input type="text" id="" v-model="list.a.value" @blur="aBlur" class="small" :readonly="!list.a.checked" maxlength="8">
            <el-select v-model="list.a.unit" class="select" placeholder="" :disabled="!list.a.checked">
              <el-option v-for="(v, k) in unit" :key="k" :value="v+coinHashUnit+'/s'"></el-option>
            </el-select>
          </div>
        </div>
        <div class="item" :class="{gray: !list.b.checked}">
          <div class="row">
            <input type="checkbox" hidden id="checkbox2" v-model="list.b.checked">
            <label for="checkbox2" :class="language">{{$t('subaccount.machine_nowork')}}</label>
          </div>
          <div class="row">
            <span>{{$t('subaccount.active_low')}}</span>
            <input type="text" id="" v-model="list.b.value" class="small" :readonly="!list.b.checked">
            <span>{{$t('unit.station')}}</span>
          </div>
        </div>
        <div class="item" :class="{gray: Object.keys(list).every(val=>!list[val].checked)}">
          <div></div>
          <div class="row">
            <span>{{$t('subaccount.interval')}}</span>
            <input type="text" id="" v-model="list.e.value" class="small" :readonly="Object.keys(list).every(val=>!list[val].checked)">
            <span>{{$t('unit.hour')}}</span>
          </div>
        </div>
      </div>
      <div class="width270 fr">
        <div class="item" :class="{gray: !list.c.checked}">
          <div class="row">
            <input type="checkbox" hidden id="checkbox3" v-model="list.c.checked">
            <label for="checkbox3" :class="language">{{$t('subaccount.notice_sms')}}</label>
          </div>
          <div class="row">
            <input type="text" id="" v-model="list.c.value" @blur="cBlur" maxlength="59" minlength="11" :placeholder="$t('subaccount.tel_more')" class="big" :readonly="!list.c.checked">
          </div>
        </div>
        <div class="item" :class="{gray: !list.d.checked}">
          <div class="row">
            <input type="checkbox" hidden id="checkbox4" v-model="list.d.checked">
            <label for="checkbox4" :class="language">{{$t('subaccount.notice_email')}}</label>
          </div>
          <div class="row">
            <input type="text" id="" v-model="list.d.value" :placeholder="$t('subaccount.email')" class="big" :readonly="!list.d.checked">
          </div>
        </div>
        <div class="item">
          <div class="row">
            <button type="button" @click="submit" class="confirm">
              <template>{{$t('btn.sure')}}</template>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getWarning, setWarning } from '@/api';
import { mapGetters } from 'vuex';

export default {
  props: {
    data: {
      type: Object,
    },
  },
  data() {
    return {
      getLoading: true,
      list: {
        a: {
          checked: false,
          value: '',
          unit: '',
        },
        b: {
          checked: false,
          value: '',
        },
        c: {
          checked: false,
          value: '',
        },
        d: {
          checked: false,
          value: '',
        },
        e: {
          value: '',
        },
      },
    };
  },
  computed: {
    ...mapGetters(['language']),
    coinHashUnit() {
      return this.data.coin_type === 'zec' ? 'Sol' : 'H';
    },
    unit() {
      return this.data.coin_type === 'zec' ? ['K', 'M', 'G', 'T', 'P'] : ['G', 'T', 'P'];
    },
  },
  created() {
    this.getWarningInfo();
  },
  methods: {
    aBlur() {
      const reg = new RegExp(/\.$/, 'g');
      while (reg.test(this.list.a.value)) {
        this.list.a.value = this.list.a.value.replace(reg, '');
      }
      if (Number(this.list.a.value) === 0) {
        this.list.a.value = '';
      }
    },
    cBlur() {
      const reg = new RegExp(/,$/, 'g');
      while (reg.test(this.list.c.value)) {
        this.list.c.value = this.list.c.value.replace(reg, '');
      }
    },
    submit() {
      if (Object.keys(this.list).some(val => this.list[val].checked)) {
        if (this.list.a.checked && !Number(this.list.a.value)) {
          this.$message({
            message: this.$t('subaccount.rate_null'),
            type: 'warning',
          });
          return;
        }
        if (this.list.a.checked && this.list.a.value >= 100000) {
          this.$message({
            message: this.$t('subaccount.rate_sure'),
            type: 'warning',
          });
          return;
        }
        if (this.list.a.checked && !this.list.a.unit) {
          this.$message({
            message: this.$t('subaccount.rate_oer_null'),
            type: 'warning',
          });
          return;
        }
        if (this.list.b.checked && !this.list.b.value) {
          this.$message({
            message: this.$t('subaccount.active_null'),
            type: 'warning',
          });
          return;
        }
        if (this.list.b.checked && this.list.b.value > 100000) {
          this.$message({
            message: this.$t('subaccount.mill_num'),
            type: 'warning',
          });
          return;
        }
        if (this.list.c.checked) {
          if (!this.list.c.value) {
            this.$message({
              message: this.$t('subaccount.tel_null'),
              type: 'warning',
            });
            return;
          }
          let cVerificationContent = '';
          this.list.c.value.split(',').forEach((val, index) => {
            if (val.length !== 11) {
              cVerificationContent += `${this.$t('subaccount.first')} ${index +
                1}${this.$t('subaccount.ove')} 、`;
            }
          });
          if (cVerificationContent) {
            if (cVerificationContent === `${this.$t('subaccount.first')}、`) {
              this.$message({
                message: this.$t('subaccount.tel_error'),
                type: 'warning',
              });
            } else {
              this.$message({
                message: `${cVerificationContent.slice(0, -1)}${this.$t(
                  'subaccount.tel_error',
                )}`,
                type: 'warning',
              });
            }
            return;
          }
        }
        const emailReg = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/;
        if (this.list.d.checked) {
          if (!this.list.d.value) {
            this.$message({
              message: this.$t('subaccount.email_null'),
              type: 'warning',
            });
            return;
          } else if (!emailReg.test(this.list.d.value)) {
            this.$message({
              message: this.$t('subaccount.email_format'),
              type: 'warning',
            });
            return;
          }
        }
        if (!this.list.a.checked && !this.list.b.checked) {
          this.$message({
            message: this.$t('subaccount.choose_rate'),
            type: 'warning',
          });
          return;
        }
        if (!this.list.c.checked && !this.list.d.checked) {
          this.$message({
            message: this.$t('subaccount.notice_method'),
            type: 'warning',
          });
          return;
        }
        if (!this.list.e.value) {
          this.$message({
            message: this.$t('subaccount.plice'),
            type: 'warning',
          });
          return;
        }
        if (this.list.e.value > 24) {
          this.$message({
            message: this.$t('subaccount.plice_24'),
            type: 'warning',
          });
          return;
        }
      }
      setWarning({
        cuid: this.data.puid,
        is_lisen_hashrate: this.list.a.checked ? 1 : 0,
        hash_rate: Number(this.list.a.value),
        hash_unit: this.list.a.unit.slice(0, 1),
        is_lisen_active_num: this.list.b.checked ? 1 : 0,
        active_num: this.list.b.value,
        is_message: this.list.c.checked ? 1 : 0,
        message_notify_lists: this.list.c.value,
        is_email: this.list.d.checked ? 1 : 0,
        email_notify_lists: this.list.d.value,
        send_time_interval: this.list.e.value,
        coin_type: this.data.coin_type,
        config_id: this.data.config_id,
      })
        .then((res) => {
          if (res.data.status === 1) {
            this.$notify({
              message: this.$t('subaccount.set_success'),
              type: 'success',
              duration: 2000,
              showClose: false,
            });
            this.$emit('toggleDialog', { showDialog: false, refresh: true });
            if (this.$route.query.type === 'setwarning') {
              this.$router.push('/pools/dashboard');
            }
          } else {
            this.$message.error(this.$t(`api.${res.data.errcode}`));
          }
        })
        .catch(() => {
          this.$message.error(this.$t('error.catchError'));
        });
    },
    getWarningInfo() {
      this.getLoading = true;
      getWarning({
        cuid: this.data.puid,
        coin_type: this.data.coin_type,
        config_id: this.data.config_id,
      })
        .then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            if (data) {
              this.list = {
                a: {
                  checked: data.is_lisen_hashrate === 1,
                  value: data.hash_rate,
                  unit:
                    data.hash_unit.length === 1
                      ? `${data.hash_unit}${this.coinHashUnit}/s`
                      : data.hash_unit,
                },
                b: {
                  checked: data.is_lisen_active_num === 1,
                  value: data.active_num,
                },
                c: {
                  checked: data.is_message === 1,
                  value: data.message_notify_lists,
                },
                d: {
                  checked: data.is_email === 1,
                  value: data.email_notify_lists,
                },
                e: {
                  value: data.send_time_interval,
                },
              };
            }
          }
          this.getLoading = false;
        })
        .catch(() => {
          this.$message.error(this.$t('error.catchError'));
          this.getLoading = false;
        });
    },
  },
  watch: {
    list: {
      handler(value) {
        const av = value.a.value.toString();
        // 第一个'.'的位置
        const firstPoint = av.indexOf('.');
        // 第二个'.'的位置
        const secondPoint = av.indexOf('.', firstPoint + 1);
        // slice位置
        let slicePosition;
        if (firstPoint === -1) {
          slicePosition = av.length;
        } else if (secondPoint === -1 || secondPoint - firstPoint > 2) {
          slicePosition = firstPoint + 3;
        } else {
          slicePosition = secondPoint;
        }
        this.list.a.value = av.slice(0, slicePosition).replace(/[^\d.]/g, '');

        const bv = value.b.value.toString();
        this.list.b.value = bv.replace(/^0|\D/g, '');

        const cv = value.c.value.toString();
        this.list.c.value = cv.replace(/，/g, ',').replace(/^,|[^\d,]/g, '');

        const ev = value.e.value.toString();
        this.list.e.value = ev.replace(/^0|\D/g, '');
      },
      deep: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog-content {
  width: 740px;
  padding: 0 50px;
  .title {
    padding: 42px 0 22px;
  }
  .item {
    &.gray {
      filter: grayscale(100%);
      filter: gray;
      color: gray !important;
    }
    .row {
      &:first-of-type {
        [type="checkbox"] + label {
          color: #70c1b3;
          font-size: 24px;
          line-height: 30px;
          height: 30px;
          display: inline-block;
          &.en{
            font-size: 20px;
          }
        }
        [type="checkbox"] + label::before {
          content: "\e67e";
          font-family: "iconfont" !important;
          font-size: 24px;
          font-style: normal;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          vertical-align: top;
          margin-right: 20px;
        }
        [type="checkbox"]:checked + label::before {
          content: "\e67d";
        }
      }
      &:nth-of-type(2) {
        /deep/ .select {
          width: 80px;
          .el-input {
            position: relative;
            .el-input__inner {
              height: 30px !important;
              border-radius: 4px;
              border: 1px solid #dcdfe6;
            }
            &.is-focus {
              .el-input__inner {
                border-color: #70c1b3;
              }
            }
          }
          .el-input__suffix {
            position: absolute;
            right: 1px;
            top: 11px;
            height: 28px;
            line-height: 28px;
            background-color: #f9f9f9;
            border-left: solid 1px #e0e0e0;
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
            .el-input__icon {
              width: 29px;
              line-height: 28px;
              &.el-icon-arrow-up:before {
                content: "\e6e9";
                font-family: "iconfont" !important;
                font-size: 12px;
                color: #70c1b3;
                font-style: normal;
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
              }
            }
          }
        }
        margin-top: 20px;
        height: 50px;
        line-height: 50px;
        font-size: 0;
        white-space: nowrap;
        span {
          font-size: 15px;
        }
        [type="text"] {
          font-size: 15px;
          height: 30px;
          line-height: 30px;
          border: none;
          outline: none;
          border-bottom: 1px solid #ccc;
          flex-shrink: 1;
          appearance: none;
          border-radius: 0;
          &.small {
            margin: 0 10px;
            width: 80px;
            text-align: center;
          }
          &.big {
            width: 100%;
          }
        }
      }
      &:last-of-type {
        margin-bottom: 40px;
      }
    }
  }
  .confirm {
    height: 40px;
    background-color: #76c1b3;
    border-radius: 3px;
    border: none;
    color: #fff;
    width: 100%;
    font-size: 18px;
    &.gray {
      filter: grayscale(100%);
      filter: gray;
    }
  }
}
</style>
